//初始化对话框
var api, W;
api = frameElement.api;
W = api.opener;
var roleId = api.data['roleId'];
//旧的权限pks( id集合字符串)
var oldModule='';
//初始化树
// ztree配置
var setting = {
	check: {
		enable: true
	},
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "_parentId"
		},
		key :{
			name :"moduleName"
		}
	}
	/*,
	callback : {
		onClick : onClickNode,
		onRightClick: OnRightClick
	}*/
};
//初始化树
var initTree = function(){
	$.ajax({
		url : 'sys/SysModule/list',
		type : "post",
		dataType : "json",
		async: false,
		data : {'beanProxy[enabled]':0,'comp':1,'isNonPage':1,'sort':'sort asc'},
		success : function(result) 
		{
			if(result.state == "200"){
				$.fn.zTree.init($("#moduleTree"), setting, result.rows).expandAll(true);;
//				$('a', $('.level2')).eq(0).click();
				//查询角色的权限
				$.ajax({
					url : 'sys/SysRights/list',
					type : "post",
					dataType : "json",
					data : {'beanProxy[enabled]':0,'comp':1,'isNonPage':1,'beanProxy[roleId]':roleId},
					success : function(result) 
					{
						if(result.state == "200"){
							var treeObj = $.fn.zTree.getZTreeObj("moduleTree");
							$.each(result.rows,function(index,node){
								oldModule+=","+node.id;
								treeObj.checkNode(treeObj.getNodeByParam("id", node.moduleId, null), true, false);
							});
				        }else{
				        	$.dialog.alert('初始化权限树数据失败！');
				        }
						
					}
				});
	        }else{
	        	$.dialog.alert('加载树数据失败！');
	        }
			
		}
	});
};


//保存角色菜单权限
var saveRoleModule = function(){
	var pks = oldModule !='' ? oldModule.substr(1):'';
	//角色id
	var moduleTree = $.fn.zTree.getZTreeObj("moduleTree");
	var nodes = moduleTree.getCheckedNodes(true);
	var array = new Array();
	$.each(nodes,function(index,node){
		array.push({moduleId:node.id,roleId:roleId});
	});
	$.dialog.confirm('你确定保存这个角色权限配置吗？', function(){
		//删除旧的权限
			$.ajax({
				url:'sys/SysRightsExt/dropExt',
				data:{pks:pks,records:JSON.stringify(array)},
				type:'post',
				async: false,
				dataType:'json',
				success:function(result){
					if(result.state !="200"){
						$.dialog.alert('更新权限失败！');
						return false;
					}
					$.dialog.alert('权限更新成功！',function(){
						cancle_module();
					});
				}
			});
	}, function(){
	});
};
//关闭事件
var cancle_module = function() {
	window.parent.frames.fnDraw();
	api.close();
};
//初始化
$(function(){
	initTree();
});